package com.my.financial.domain;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.my.financial.controller.form.LoginForm;
import com.my.financial.controller.form.PageInfo;
import com.my.financial.controller.form.QueryForm;
import com.my.financial.controller.form.RegisteForm;
import com.my.financial.repository.FinancialAccountRepository;
import com.my.financial.repository.FinancialItemRepository;
import com.my.financial.repository.UserRepository;

@Component
public class FinancialServiceImpl implements FinancialService {
	@Autowired
	private UserRepository userRepository;

	@Autowired
	private FinancialAccountRepository financialAccountRepository;

	@Autowired
	private FinancialItemRepository financialItemRepository;
	
	@Transactional
	public User login(LoginForm loginForm) {
		String name = loginForm.getUserName();
		String ps = loginForm.getPassword();
		return userRepository.findByUserNameAndPassword(name, ps);
	}
	
	@Transactional
	public void register(RegisteForm registeForm) {
		User user = formToUser(registeForm);
		user.setId(userRepository.save(user));
		FinancialAccount account = new FinancialAccount();
		account.setAccountType("现金账户");
		account.setAccount("现金口袋");
		account.setBalance(new BigDecimal(0));
		account.setUser(user);
		financialAccountRepository.save(account);
	}
	
	@Transactional
	public void addMember(String member, Long userId) {
		userRepository.addMember(member,userId);
	}
	
	@Transactional
	public void deleteMember(String member, Long userId) {
		userRepository.deleteMember(member,userId);
	}
	
	@Transactional
	public List<String> findAllMembers(Long userId) {
		String[] arr = userRepository.findAllMembersById(userId).split(",");
		return Arrays.asList(arr);
	}

	@Transactional(timeout=60)
	public void saveUser(User user) {
		userRepository.save(user);
	}
	
	@Transactional
	public void deleteUserById(Long id) {
		User user = new User();
		user.setId(id);
		userRepository.delete(user);
	}
	
	@Transactional
	public User findUserById(String userId) {
		return userRepository.findById(Long.parseLong(userId));
	}
	
	@Transactional
	public void saveAccount(FinancialAccount account) {
		financialAccountRepository.save(account);
	}
	
	@Transactional
	public void deleteAccountById(Long id) {
		FinancialAccount financialAccount = new FinancialAccount(id);
		financialAccountRepository.delete(financialAccount);
	}
	
	@Transactional
	public void saveItem(FinancialItem item) {
		FinancialAccount account = financialAccountRepository.findByIdOnLockMode(item.getAccount().getId());
		if (item.getType().equals("收入")) {
			account.setBalance(account.getBalance().add(item.getAmount()));
			item.setAccount(account);
		} else if (item.getType().equals("支出")) {
			account.setBalance(account.getBalance().subtract(item.getAmount()));
			item.setAccount(account);
		}
		financialItemRepository.save(item);
	}
	
	@Transactional
	public void batchDeleteItemById(String multiId) {
		financialItemRepository.batchDelete(multiId);
	}
	
	@Transactional
	public List<FinancialItem> findItemByQueryForm(QueryForm queryForm,
			PageInfo pageInfo) {
		return financialItemRepository.findByQueryForm(queryForm, pageInfo);
	}

	@Transactional
	public PageInfo findPageInfo(QueryForm queryForm, PageInfo pi) {
		return financialItemRepository.findPageInfo(queryForm, pi);
	}

	@Transactional
	public boolean checkUserName(String userName) {
		return userRepository.findByUserName(userName)==null?true:false;
	}

	@Transactional
	public List<FinancialAccount> findAllAccount(Long userId) {
		return financialAccountRepository.findAllAccount(userId);
	}
	
	@Transactional
	public QueryForm getStartAndEndTime(String dateType, String dateNum) {
		QueryForm queryForm = new QueryForm();
		Calendar cal = Calendar.getInstance();
		DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		String startTime = null; 
		String endTime = null;
		
		if (StringUtils.isBlank(dateType)) {
			return null;
		} else if (dateType.equals("月")) {
	        cal.set(Calendar.DAY_OF_MONTH,1);
			if (StringUtils.isNoneBlank(dateNum)) {
				cal.add(Calendar.MONTH, Integer.parseInt(dateNum));
			}
			startTime = dateFormat.format(cal.getTime());
			cal.add(Calendar.MONTH,1);
			endTime = dateFormat.format(cal.getTime());
		} else if (dateType.equals("周")) {
			cal.add(Calendar.DATE, -1);
			cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
			if (StringUtils.isNoneBlank(dateNum)) {
				cal.add(Calendar.DATE, 7 * (Integer.parseInt(dateNum)));
			}
			startTime = dateFormat.format(cal.getTime());
			cal.add(Calendar.DATE, 7);
			endTime = dateFormat.format(cal.getTime());
		} else if (dateType.equals("日")) {
			if (StringUtils.isNoneBlank(dateNum)) {
				cal.add(Calendar.DATE, Integer.parseInt(dateNum));
			}
			startTime = dateFormat.format(cal.getTime());
			cal.add(Calendar.DATE,1);
			endTime = dateFormat.format(cal.getTime());
		}
		queryForm.setStarttime(startTime);
		queryForm.setEndtime(endTime);
		return queryForm;
	}
	
	public String getDateRange(QueryForm queryForm,String dateType) {
		final String startTime = queryForm.getStarttime();
		final String endTime = queryForm.getEndtime();
		String dateRange = null;
		if(dateType.equals("月")){
			String[] start = startTime.split("-");
			dateRange = start[0]+"年"+start[1]+"月份";
		}else if(dateType.equals("周")){
			dateRange = startTime+"至"+endTime;
		}else if(dateType.equals("日")){
			dateRange = startTime;
		}
		return dateRange;
	}
	
	private User formToUser(RegisteForm registeForm) {
		User user = new User();
		user.setUserName(registeForm.getUserName());
		user.setPassword(registeForm.getPassword());
		user.setEmail(registeForm.getEmail());
		user.setAllMembers("本人,家庭公用");
		return user;
	}
}
